package com.thrc.borrow.controller;

import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.thrc.borrow.entity.SystemSetting;
import com.thrc.borrow.entity.User;
import com.thrc.borrow.service.UserService;
import com.thrc.borrow.utils.CacheUtil;
import com.thrc.borrow.utils.Container;
import com.thrc.borrow.utils.ResponseUtil;
import com.thrc.borrow.utils.ReturnCode;
import com.thrc.borrow.utils.SecretUtil;
import com.thrc.borrow.vo.UserVo;

@Controller
@RequestMapping("/user")
public class UserController {

	@Autowired
	private UserService userService;

	@RequestMapping("/list/page")
	public String goUserJsp() {

		return "sys/userList";
	}

	@RequestMapping("/getUserById")
	public void selectById(HttpServletResponse response, User t) {
		UserVo vo = userService.selectById(t);
		ResponseUtil.print(response, vo);
	}

	@RequestMapping("/getUserByPhone")
	public void getUserByPhone(HttpServletResponse response, User t) {
		UserVo user = userService.selectByPhone(t);
		ResponseUtil.print(response, user == null ? ReturnCode.SUCCESS_CODE : ReturnCode.FAIL_CODE);
	}

	@RequestMapping("/selectAllUser")
	public void selectAll(HttpServletResponse response, User t) {
		try {
			List<UserVo> UserList = userService.selectAll(t);
			ResponseUtil.print(response, UserList);
		} catch (Exception e) {
			e.printStackTrace();
			ResponseUtil.print(response, ReturnCode.FAIL_CODE, e.getMessage());
		}
	}

	@RequestMapping("/selectUserListByPage")
	public void selectByPage(HttpServletResponse response, User t) {

		JSONObject retJson = new JSONObject();
		try {
			int totleCount = userService.selectCount(t);
			retJson.put("total", totleCount);
			if (totleCount == 0) {
				retJson.put("data", null);
				ResponseUtil.print(response, retJson);
				return;
			}
			List<UserVo> UserList = userService.selectByPage(t);
			retJson.put("data", UserList);
			ResponseUtil.print(response, retJson);
		} catch (Exception e) {
			e.printStackTrace();
			ResponseUtil.print(response, ReturnCode.FAIL_CODE, e.getMessage());
		}
	}

	@RequestMapping("/getRoleListById")
	public void getRoleListById(HttpServletResponse response, User t) {
		ResponseUtil.print(response, userService.getRoleListById(t));
	}

	@RequestMapping("/login")
	public void login(HttpServletResponse response, HttpServletRequest request, User t,
			@RequestParam(value = "rememberMe", required = false) String rememberMe) {
		try {
			UserVo userVo = userService.selectByPhone(t);
			if (userVo == null) {
				ResponseUtil.print(response, ReturnCode.ERROR_CODE, "用户不存在");
				return;
			}
			String pwd = SecretUtil.getMd5Pwd(t.getPwd(), userVo.getHash());
			if (pwd.equals(userVo.getPwd())) {
				t.setId(userVo.getId());
				t.setPwd(pwd);
				userService.login(t);
				request.getSession().setAttribute("user", userVo);
				request.getSession().setAttribute("userPhone", userVo.getPhone());
				if ("yes".equalsIgnoreCase(rememberMe)) {
					Cookie cookie = new Cookie("rememberMe", userVo.getId() + "");
					// 保存一周
					cookie.setMaxAge(60 * 60 * 24 * 7);
					response.addCookie(cookie);
				}
				ResponseUtil.print(response, ReturnCode.SUCCESS_CODE, "登录成功", t);
			} else {
				ResponseUtil.print(response, ReturnCode.ERROR_CODE, "密码不正确");
				return;
			}
		} catch (Exception e) {
			e.printStackTrace();
			ResponseUtil.print(response, ReturnCode.FAIL_CODE, e.getMessage());
		}
	}

	@RequestMapping("/logout")
	public void logout(HttpServletResponse response, HttpServletRequest request, User t) {
		try {
			UserVo sessionUser = (UserVo) request.getSession().getAttribute("user");
			if (sessionUser != null) {
				request.getSession().removeAttribute("user");
				request.getSession().invalidate();
			}
			response.sendRedirect("/system/tologin");
		} catch (Exception e) {
			e.printStackTrace();
			ResponseUtil.print(response, ReturnCode.FAIL_CODE, e.getMessage());
		}
	}

	@RequestMapping("/updateUser")
	public void update(HttpServletResponse response, User t) {
		try {
			User queryUser = new User();
			queryUser.setPhone(t.getPhone());
			List<UserVo> userList = userService.selectAll(queryUser);
			if (userList.size() > 1) {
				// 与已有电话号码重复
				ResponseUtil.print(response, ReturnCode.FAIL_CODE, "与已有电话号码重复");
				return;
			}

			userService.update(t);
			ResponseUtil.print(response, ReturnCode.SUCCESS_CODE);
		} catch (Exception e) {
			e.printStackTrace();
			ResponseUtil.print(response, ReturnCode.FAIL_CODE, e.getMessage());
		}
	}

	@RequestMapping("/deleteUser")
	public void delete(HttpServletResponse response, User t) {

		try {
			userService.delete(t);
			ResponseUtil.print(response, ReturnCode.SUCCESS_CODE);
		} catch (Exception e) {
			e.printStackTrace();
			ResponseUtil.print(response, ReturnCode.FAIL_CODE, e.getMessage());
		}
	}

	@RequestMapping("/insertUser")
	public void insert(HttpServletResponse response, HttpServletRequest request, User t) {

		try {
			User queryUser = new User();
			queryUser.setPhone(t.getPhone());
			List<UserVo> userList = userService.selectAll(queryUser);
			if (userList.size() > 0) {
				// 与已有电话号码重复
				ResponseUtil.print(response, ReturnCode.FAIL_CODE, "与已有电话号码重复");
				return;
			}

			String hash = SecretUtil.getHash();
			String defaultPwd = CacheUtil.getCacheDate(Container.CACHE_KEY.SYS_SETING, SystemSetting.class)
					.getDefaultPwd();

			t.setPwd(SecretUtil.getMd5Pwd(defaultPwd, hash));
			t.setHash(hash);
			userService.insert(t);
			ResponseUtil.print(response, ReturnCode.SUCCESS_CODE);
		} catch (Exception e) {
			e.printStackTrace();
			ResponseUtil.print(response, ReturnCode.FAIL_CODE, e.getMessage());
		}
	}

	@RequestMapping("/phone/check")
	public void checkPhoneExsit(HttpServletResponse response, User t) {
		UserVo user = userService.selectByPhone(t);
		if (user == null) {
			ResponseUtil.print(response, ReturnCode.SUCCESS_CODE);
		} else {
			ResponseUtil.print(response, ReturnCode.FAIL_CODE);
		}
	}

	@RequestMapping("/register")
	public void registerUser(HttpServletRequest request, HttpServletResponse response, User t, 
			@RequestParam("code") String code) {
		try {
			//判断短信验证码
			Object sessionCode = request.getSession().getAttribute("reg_code");
			if (sessionCode == null) {
				ResponseUtil.print(response, ReturnCode.FAIL_CODE, "请发送验证码");
				return;
			} else if(!code.equals(sessionCode)) {
				ResponseUtil.print(response, ReturnCode.FAIL_CODE, "验证码输入不正确");
				return;
			}
		/*	if(!StringUtils.isEmpty(t.getRefferee())) {
				User u = new User();
				u.setPhone(t.getRefferee());
				List<UserVo> query = userService.selectByPage(u);
				if(query != null && query.size() <= 0) {
					ResponseUtil.print(response, ReturnCode.FAIL_CODE, "邀请码不存在");
					return;
				}
			}*/
			
			User queryUser = new User();
			queryUser.setPhone(t.getPhone());
			List<UserVo> userList = userService.selectAll(queryUser);
			if (userList.size() > 0) {// 与已有电话号码重复
				ResponseUtil.print(response, ReturnCode.FAIL_CODE, "与已有电话号码重复");
				return;
			}
			String hash = SecretUtil.getHash();
			t.setPwd(SecretUtil.getMd5Pwd(t.getPwd(), hash));
			t.setHash(hash);
			userService.insert(t);
			// 添加用户session
			request.getSession().setAttribute("user", t);
			request.getSession().setAttribute("userPhone", t.getPhone());
			ResponseUtil.print(response, ReturnCode.SUCCESS_CODE, "注册成功", t);
		} catch (Exception e) {
			e.printStackTrace();
			ResponseUtil.print(response, ReturnCode.FAIL_CODE, e.getMessage());
		}
	}

	/**
	 * 找回密码-修改密码
	 * 
	 * @param request
	 * @param response
	 * @param t
	 */
	@RequestMapping("/pwd/find")
	public void findUserPwd(HttpServletRequest request, HttpServletResponse response, User t,
			@RequestParam("code") String code) {
		//判断短信验证码
		Object sessionCode = request.getSession().getAttribute("findPwd_code");
		if (sessionCode == null) {
			ResponseUtil.print(response, ReturnCode.FAIL_CODE, "请发送验证码");
			return;
		} else if(!code.equals(sessionCode)) {
			ResponseUtil.print(response, ReturnCode.FAIL_CODE, "验证码输入不正确");
			return;
		}
		
		if (t.getPhone() == null || "".equals(t.getPhone().trim())) {
			ResponseUtil.print(response, ReturnCode.FAIL_CODE, "手机号不能为空");
			return;
		}
		UserVo userCheck = userService.selectByPhone(t);
		if (userCheck == null) {
			ResponseUtil.print(response, ReturnCode.FAIL_CODE, "该手机号不存在，请注册后再试");
			return;
		}
		// 添加
		try {
			User user = new User();
			user.setId(userCheck.getId());
			user.setPwd(SecretUtil.getMd5Pwd(t.getPwd(), userCheck.getHash()));
			userService.update(user);
			ResponseUtil.print(response, ReturnCode.SUCCESS_CODE);
		} catch (Exception e) {
			ResponseUtil.print(response, ReturnCode.FAIL_CODE, "找回密码失败，请稍后再试");
		}
	}
	
	/**
	 * 实名认证
	 * @param t
	 */
	@RequestMapping("/realname/auth")
	public void realnameAuth(HttpServletRequest request, HttpServletResponse response, User t) {
		UserVo vo = userService.selectById(t);
		if(vo == null) {
			ResponseUtil.print(response, ReturnCode.FAIL_CODE, "请登录后再试");
			return;
		}
		if(StringUtils.isEmpty(t.getRealname())) {
			ResponseUtil.print(response, ReturnCode.FAIL_CODE, "姓名不能为空");
			return;
		}
		if(StringUtils.isEmpty(t.getIdNo())) {
			ResponseUtil.print(response, ReturnCode.FAIL_CODE, "身份证号不能为空");
			return;
		}
		try {
			userService.update(t);
			ResponseUtil.print(response, ReturnCode.SUCCESS_CODE);
		} catch (Exception e) {
			e.printStackTrace();
			ResponseUtil.print(response, ReturnCode.FAIL_CODE, "实名认证失败");
			return;
		}
	}
	
	/**
	 * 设置支付密码
	 * @param t
	 */
	@RequestMapping("/dealpwd/set")
	public void dealpwdSet(HttpServletRequest request, HttpServletResponse response, User t) {
		UserVo vo = userService.selectById(t);
		if(vo == null) {
			ResponseUtil.print(response, ReturnCode.FAIL_CODE, "请登录后再试");
			return;
		}
		try {
			userService.update(t);
			ResponseUtil.print(response, ReturnCode.SUCCESS_CODE);
		} catch (Exception e) {
			e.printStackTrace();
			ResponseUtil.print(response, ReturnCode.FAIL_CODE, "设置支付密码失败");
			return;
		}
	}
	
}
